import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ride_rex/main/mine/edit_info/edit_info_logic.dart';
import 'package:ride_rex/net/common_net.dart';
import 'package:ride_rex/service/oss_service.dart';
import 'package:ride_rex/service/user_service.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import '../../service/log_service.dart';
import '../../ui/common_dialogs.dart';

class MineLogic extends GetxController with CommonLife, OnceClick {
  @override
  void onReady() {
    super.onReady();
    UserService.instance.getCacheMineInfoBean();
  }

  @override
  void onClose() {
    super.onClose();
  }

  @override
  void pageBack() {
    super.pageBack();
  }

  Future changeAvatar() async {
    LMLogManager.stat(page: 'editavatar');

    ActionBottomSheet.actionSheet(items: [
      ActionSheetConfig(
        text: 'Take Photo',
        onTap: () async {
          CommonPrivilegeStatus status = await CommonPrivilege.camera();
          if (!status.result) {
            CommonDialogs.twoButton(
              title: status.title,
              description: status.message,
              cancelTitle: YlmGlobalConfig().actionSheetConfig.cancelTitle,
              confirmTitle: YlmGlobalConfig().actionSheetConfig.confirmTitle,
              onConfirm: () => CommonPrivilege.openSettings(),
            );
            return;
          }
          AssetEntity? assetEntity = await ActionPicker.camera(locale: const Locale('en', 'US'));
          if (assetEntity == null) return;
          String filePath = (await assetEntity.file)?.path ?? '';
          upload(filePath);
        },
      ),
      ActionSheetConfig(
        text: 'Choose From Library',
        onTap: () async {
          CommonPrivilegeStatus status = await CommonPrivilege.photos();
          if (!status.result) {
            CommonDialogs.twoButton(
              title: status.title,
              description: status.message,
              cancelTitle: YlmGlobalConfig().actionSheetConfig.cancelTitle,
              confirmTitle: YlmGlobalConfig().actionSheetConfig.confirmTitle,
              onConfirm: () => CommonPrivilege.openSettings(),
            );
            return;
          }

          List<AssetEntity> list = await ActionPicker.assets() ?? [];
          if (list.isEmpty) return;
          String filePath = (await list.first.file)?.path ?? '';
          upload(filePath);
        },
      ),
    ]);
  }

  void upload(String filePath) {
    startOnce(() async {
      OssResultBean? bean = await OssService.uploadFile(filePath);
      String filename = bean?.filename ?? '';
      if (filename.notEmpty) await ApiUpdateInfo.updateAvatar(filename).post();
      await UserService.instance.getCacheMineInfoBean(true);
      Loading.dismiss();
    });
  }
}
